package com.circle.service;

import com.circle.model.entity.AjaxJson;
import com.circle.model.entity.DccInternalFileEntity;
import com.circle.model.module.ConfigData;
import com.circle.model.module.OkPost;
import com.circle.model.module.log.LoggerABC;
import com.circle.model.module.log.LoggerBuilder;
import com.circle.model.util.ConfigDataFactory;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Map;

public class ExportSpecService {

    public void export(DccInternalFileEntity internalFile, ConfigData configData) {
        LoggerABC loggerABC = LoggerBuilder.build();
        try{
            AjaxJson returnJson = new OkPost(configData.getUrl() + "dccSpecController.do?getPathByInternalid")
                    .addFormParam("internalid", internalFile.getId())
                    .addCookie("DCC_TOKEN", configData.getToken())
                    .execute();
            if (!returnJson.isSuccess()) {
                return;
            }
            File interFile = new File(configData.getExportDir(), internalFile.getSpecNo());
            if (!interFile.exists()) {
                FileUtils.forceMkdir(interFile);
            }
            File docx = new File(interFile, "docx");
            if (!docx.exists()) {
                FileUtils.forceMkdir(docx);
            }
            Map<String, String> dataMap = (Map<String, String>) returnJson.getObj();
            for (String key : dataMap.keySet()) {
                String path = dataMap.get(key);
                File srcFile = new File(path);
                if (!srcFile.exists()) {
                    loggerABC.logMessage(LoggerABC.WARN, "Error occurred during ExportSpecService export: File system element for parameter 'source' does not exist: " + srcFile.getAbsolutePath());
                    continue;
                }
                File destFile = new File(docx, key);
                FileUtils.copyFile(srcFile, destFile, true); // 第三个参数为true表示复制时保留文件属性
            }
        }catch (Exception e){
            loggerABC.setException(e);
            loggerABC.logMessage(LoggerABC.ERROR, "Error occurred during ExportSpecService export: " + e.getMessage());
        }
    }



}
